package com.hyopt.modules.app.controller;

import cn.hutool.core.util.StrUtil;
import com.alipay.api.internal.util.codec.Base64;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;

/**
 * @ClassName AESDemo
 * @Description TODO
 * @Author lijie
 * @Date 2023/3/14 15:27 星期二
 * @Version 1.0
 */
@Slf4j
public class AESDemo {
    public static final String AESKey = "hvxtjqcroeebplqy";

    public static void main(String[] args) throws Exception {
        String sign = aesEncrypt("Hello World!",AESKey,"utf-8");
        log.info("加签后的值：{}",sign);
        String relase = aesDecrypt("uly1HGWTKtqJn4rczuFcdw==",AESKey,"utf-8");
        log.info("解签后的值：{}",relase);
    }


    /**
     * AES解密
     *
     * @param content
     * @param key
     * @param charset
     * @return
     * @throws Exception
     */
    public static String aesDecrypt(String content, String key, String charset)
            throws Exception {
        if (StrUtil.isBlank(content)) {
            return content;
        }
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            String str = "0000000000000000";
            IvParameterSpec iv = new IvParameterSpec(str.getBytes()); //0000000000000000.getBytes()
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"), iv);
            byte[] cleanBytes = cipher.doFinal(Base64.decodeBase64(content.getBytes(Charset.forName("utf-8"))));
            return new String(cleanBytes, charset);
        } catch (Exception e) {
            log.info("AES解密异常，content:{}，charset:{}，异常信息：{}", content, charset, e.getMessage());
            throw new Exception("111111");
        }
    }
    /**
     * AES加密
     *
     * @param content
     * @param aesKey
     * @param charset
     * @return
     * @throws Exception
     */
    public static String aesEncrypt(String content, String aesKey, String charset)
            throws Exception {
        if (StrUtil.isBlank(content)) {
            return content;
        }
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); //AES/CBC/PKCS5Padding
            String str = "0000000000000000";
            IvParameterSpec iv = new IvParameterSpec(str.getBytes()); //0000000000000000.getBytes()
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(aesKey.getBytes(), "AES"), iv); //AES
            byte[] encryptBytes = cipher.doFinal(content.getBytes(charset));
            return new String(Base64.encodeBase64(encryptBytes));
        } catch (Exception e) {
            log.info("AES加密异常，content:{}，charset:{}，异常信息：{}", content, charset, e.getMessage());
            throw new Exception("111111");
        }
    }
}
